import axios from "axios";
import qs from "qs";
import utils from "./utils";
import config from "./config";
import store from "../../store";
import router from "../../router";

let siteInfos = utils.getStorage("SITE_INFOS");
store.commit("setSiteInfos", siteInfos);

axios.defaults.timeout = 180000;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// axios.defaults.headers.get['Content-Type'] = 'application/json';
axios.defaults.baseURL = config.baseApi;
// axios.defaults.withCredentials = true

axios.interceptors.request.use(
  function (config) {
    // if(siteInfos){
    // config.headers.Authorization = 'bearer '+ siteInfos.token
    // }
    return config;
  },
  function (err) {
    return Promise.reject(err);
  }
);
// axios兼容IE 8-9
axios.interceptors.response.use((response) => {
  // IE 8-9
  if (
    response.data == null &&
    response.config.responseType === "json" &&
    response.request.responseText != null
  ) {
    try {
      // eslint-disable-next-line no-param-reassign
      response.data = JSON.parse(response.request.responseText);
    } catch (e) {
      // ignored
    }
  }
  return response;
});
function request(options) {
  siteInfos = store.state.siteInfos;
  let dataParams = options.data;
  let data = {};
  let requestUrl = options.url;
  options.method = options.method || "get";
  // if(siteInfos && requestUrl.indexOf('/login')<0){
  // 	data.token = siteInfos.token
  // }
  for (let key in dataParams) {
    data[key] = dataParams[key];
  }

  if (options.method.toLowerCase() === "get") {
    data = qs.stringify(data);
    if (data.length > 0) {
      requestUrl += requestUrl.indexOf("?") >= 0 ? "&" : "?";
      requestUrl += data;
    }
  }

  let isPostForm =
    (requestUrl.indexOf("/business/") >= 0 ||
      requestUrl.indexOf("/check/") >= 0) &&
    options.method.toLowerCase() == "post";

  let pathList = [
    "/notice/notice/register",
    "/systemsetup/systemsetup/identityVerification",
    "/systemsetup/systemsetup/passwordReset",
    "/systemsetup/systemsetup/register",
    "/systemsetup/systemsetup/getVerificationCode",
  ];
  let auth = "";
  if (
    options.url == "/systemsetup/systemsetup/logout2" ||
    options.url == "/systemsetup/systemsetup/refresh"
  ) {
    auth = "Bearer " + siteInfos.refresh_token;
  } else if (
    options.url.indexOf("/login") < 0 &&
    pathList.indexOf(options.url) < 0
  ) {
    auth = "Bearer " + siteInfos.token;
  }
  let headerAuth = {};
  if (auth) {
    headerAuth = { Authorization: auth };
  }

  return new Promise(function (resolve, reject) {
    axios({
      url: requestUrl,
      method: options.method,
      responseType: options.responseType || "json",
      data: data,
      headers: Object.assign({}, headerAuth),
    })
      .then((res) => {
        if (res.data.code == "401") {
          if (options.url == "/systemsetup/systemsetup/refresh") {
            router.replace("/login");
            reject({});
          } else {
            refreshToken(
              () => {
                request(options).then(
                  (reRes) => {
                    resolve(reRes);
                  },
                  (reErr) => {
                    // reject({})
                    reject(reErr);
                  }
                );
              },
              () => {
                reject({});
              }
            );
          }
        } else if (res.data.code == "0") {
          resolve(res.data);
        } else {
          // reject({})
          reject(res.data);
        }
      })
      .catch((error) => {
        if (error.response) {
          if (error.response.status == "401") {
            router.replace("/login");
          } else {
            // reject({})
            reject({ msg: error.response.data.message } || "系统错误");
          }
        } else {
          // reject({})
          reject({ msg: error.message || "系统错误" });
        }
      });
  });
}
function refreshToken(cbk) {
  request({
    method: "POST",
    url: "/systemsetup/systemsetup/refresh",
  }).then(
    (res) => {
      siteInfos = store.state.siteInfos;
      siteInfos.token = res.data.token;
      store.commit("setSiteInfos", siteInfos);
      cbk && cbk();
    },
    (err) => {
      //
    }
  );
}
// refreshToken()
function get(url, params) {
  return request({
    method: "GET",
    url: url,
    data: params,
  });
}
function post(url, params) {
  return request({
    method: "POST",
    url: url,
    data: params,
  });
}
export { request, axios, get, post };
